//检测依赖项数组有无变化
import {useRef} from "react";

function depsAreaSame(oldDeps: any[], deps: any[]): boolean {
    //依赖项数组的地址对比
    if (oldDeps === deps) {
        return true;
    }
    //数组的第一层对比
    for (let i  in   oldDeps) {
        if (oldDeps[i] !== deps[i]) {
            return false;
        }
    }
    return true;
}

export default function useCreation<T>(factory: () => T, deps: any[]) {
    const {current} = useRef({
        deps,
        obj: <undefined | T>undefined,
        initialized: false,
    });
    if (current.initialized === false || !depsAreaSame(current.deps, deps)) {
        current.deps = deps;
        current.obj = factory();
        current.initialized = true
    }
    return current.obj as T;

}
